package com.jiexin.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @Author: Jay_Liu
 * @Description: 日期工具类
 * @Date: Created in 21:26 2018/7/19
 * @Modified By:
 */
public class DateUtil {

    /**
     * 比较字符串日期大小
     * @param DATE1
     * @param DATE2
     * @return 1大于2则返回1,1小于2则返回-1,否则返0
     */
    public static int compare_date(String DATE1, String DATE2) {

        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        try {
            Date dt1 = df.parse(DATE1);
            Date dt2 = df.parse(DATE2);
            if (dt1.getTime() > dt2.getTime()) {
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取当前时间前一天的时间戳
     * return 前一天的时间戳
     */
    public static String theDayBefore(){

        Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
        ca.setTime(new Date());
        ca.add(Calendar.DATE, -1);  //前一天
        Date lastMonth = ca.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String format = sdf.format(lastMonth);
        return format;
    }

    /**
     * 给定最后修改时间和当前时间比较
     *
     * @param value
     *            最后修改时间
     * @return (当前时间-最后修改时间)后取其分钟数
     */
    public static long comparedTime(Date value) {
        Calendar time = Calendar.getInstance();
        Date currentDate = time.getTime();
        long curTime = currentDate.getTime();
        long modTime = value.getTime();
        long diff = 0;
        if (curTime > modTime) {
            diff = curTime - modTime;
            long day = diff / (24 * 60 * 60 * 1000);
            long hour = (diff / (60 * 60 * 1000) - day * 24);
            diff = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
        }
        return diff;
    }


    /**
     * 根据时间戳获取目前的时间
     * @param dateFormat 时间戳
     * @return 获取当地时间
     */
    public static String getLocalTime(String dateFormat){

        Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
        ca.setTime(new Date());
        Date lastMonth = ca.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        String format = sdf.format(lastMonth);
        return format;
    }

    public static void main(String[] args) {
        String yyyyMMdd = getLocalTime("yyyyMMdd");
        System.out.println(yyyyMMdd);
    }

}
